package com.future;

import com.future.util.TreeNode;

/**
 * 给定一个二叉树，检查它是否是镜像对称的。
 */
public class Solution_isSymmetric_101 {

    public static void main(String[] args) {
        TreeNode L = new TreeNode(2, new TreeNode(3), new TreeNode(3));
        TreeNode R = new TreeNode(2, new TreeNode(3), new TreeNode(3));
        TreeNode head = new TreeNode(1, L, R);
        System.out.println(isSymmetric(head));
    }

    public static boolean isSymmetric(TreeNode root) {
        return isMirror(root.left, root.right);
    }

    /**
     * 注意一点：值传递，
     * 只要出现false,层层返回，不再递归
     *
     * @param nodeLeft
     * @param nodeRight
     * @return
     */
    private static boolean isMirror(TreeNode nodeLeft, TreeNode nodeRight) {
        if (nodeLeft == null ^ null == nodeRight) {
            return false;
        }
        if (null == nodeLeft && null == nodeRight) {
            return true;
        }
        boolean b;
        if (nodeLeft.val == nodeRight.val) {
            // 左边树的左边值等于右边树的右边值
            b = isMirror(nodeLeft.left, nodeRight.right);
            if (!b) {
                return false;
            }
            // 左边树的右边值等于右边树的左边值
            b = isMirror(nodeLeft.right, nodeRight.left);
            if (!b) {
                return false;
            }
        } else {
            return false;
        }
        return true;
        // 跟上面等价，上面只是为了更方便debugger
        /*return nodeLeft.val == nodeRight.val
                && isMirror(nodeLeft.left, nodeRight.right)
                && isMirror(nodeLeft.right, nodeRight.left);*/
    }
}
